<template>
  <el-form :model="user" :rules="rules" ref="userForm" label-width="100px" class="updatePsd-form">
    <el-form-item label="旧密码" prop="oldPassword">
      <el-input v-model.trim="user.oldPassword" type="password" show-password size="large" />
    </el-form-item>
    <el-form-item label="新密码" prop="newPassword">
      <el-input v-model.trim="user.newPassword" type="password" show-password size="large" />
    </el-form-item>
    <el-form-item label="确认密码" prop="confirmPassword">
      <el-input
        v-model.trim="user.confirmPassword"
        type="password"
        show-password
        size="large"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('userForm')">保存</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { updatePsd } from "@/api/user";
export default {
  props: {
    user: {
      type: Object,
      default: () => {
        return {
          oldPassword: "",
          newPassword: "",
          confirmPassword: "",
        };
      },
    },
  },
  data() {
    // 确认密码自定义校验规则
    const validateConfirmPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请填写确认密码"));
      } else if (value !== this.user.newPassword) {
        callback(new Error("确认密码与新密码不一致"));
      } else {
        callback();
      }
    };

    return {
      rules: {
        oldPassword: [
          { required: true, message: "请填写旧密码!", trigger: "blur" },
        ],
        newPassword: [
          { required: true, message: "请填写新密码", trigger: "blur" },
          { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
        ],
        confirmPassword: [
          { required: true, message: "请填写确认密码", trigger: "blur" },
          { validator: validateConfirmPassword, trigger: "blur,change" },
        ],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = { oldPassword: this.user.oldPassword,newPassword: this.user.newPassword };
          updatePsd(params).then((res) => {
            if (res.code == 0) {
              this.$message.success("修改成功");
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
          return false;
        }
      });
    },
  },
};
</script>
<style lang="scss">
.updatePsd-form{
  .el-form-item{ 
    margin-bottom: 25px;
  }
}
</style>
